$(() => {
    const $container = $('body > .container');
    // 查看患者详情
    $container.on('openExam', (_, data) => {
        //获取表格选择的行,打开新的窗体，并且传递Oid
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要查看的检查', 'error');
        } else {
            window.open(`/register/detail?oid=${encodeURIComponent(oids[0])}`, '_blank');
        }
    });
    // 查看申请单
    $container.on('viewApply', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要查看的申请单', 'error');
        } else {
            //工作流
            $.invokeAction('查看申请单',
                `/api/technician/view-apply/${oids[0]}`,
                null,
                {
                    type: 'GET',
                    actionUrl: '/api/workflow/invoke'
                });
        }
    });
    // 更换设备
    $container.on('changeDevice', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要更换设备的检查', 'error');
        } else {
            //弹出窗口
            openDevicePopup(oids[0]).then(result => {
                //调用接口更换设备
                $.get(`/api/technician/change-device/exam/${oids[0]}/device/${result[0]}`)
            });
        }
    });
    // 呼叫下一位
    $container.on('callNext', (_, data) => {
        ris.ajax(`/api/technician/call-next`).then(result => {
            if (result.info) {
                DevExpress.ui.dialog.alert(result.info, '呼叫患者');
            }
            refreshDataGrid(data);
        });
    });
    // 呼叫患者（具体患者）
    $container.on('call', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要呼叫的检查', 'error');
        } else {
            //调用接口
            ris.ajax(`/api/technician/call/${oids[0]}`).then(result => {
                refreshDataGrid(data);
            });
        }
    });
    // 开始检查
    $container.on('start', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要开始检查的检查', 'error');
        } else {
            ris.ajax(`/api/technician/start-exam/${oids[0]}`).then(result => {
                DevExpress.ui.notify('开始检查', 'success');
                refreshDataGrid(data);
            });
        }
    });
    // 开始检查
    $container.on('startExam', (_, data) => {
        if (data) {
            const { examGrid } = data;
            if (examGrid) {
                let rowsData = (examGrid && examGrid.getSelectedRowsData());
                let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
                if (oids.length === 0) {
                    DevExpress.ui.notify('请选择需要开始检查的检查', 'error');
                } else {
                    ris.ajax(`/api/technician/${oids[0]}/start-exam`).then(result => {
                        if (result.success) {
                            // window.localStorage.setItem('current-video-capturing-id', result.data);
                            window.open(`/report/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                        }
                    });
                }
            }
        }
    });
    // 完成检查
    $container.on('completed', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要完成的检查', 'error');
        } else {
            ris.ajax(`/api/technician/completed-exam/${oids[0]}`).then(result => {
                DevExpress.ui.notify('完成检查', 'success');
                refreshDataGrid(data);
            });
        }
    });
    // 检查参数记录
    $container.on('checkParameterRecord', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要记录的检查', 'error');
        } else {
            //调用工作流
            $.invokeAction('检查参数记录', `/api/technician/check-paramter-record`, { examId: oids[0] }, { actionUrl: '/api/workflow/invoke' });
        }
    });
    // 紧急登记：点击按钮之后，调用工作流新建一条数据（数据流有可能弹出一个窗体）
    $container.on('emergencyRegist', (_, data) => {
        $.invokeAction('紧急登记', `/api/technician/emergency-regist`, null, { actionUrl: '/api/workflow/invoke' }).then(result => {
            refreshDataGrid(data);
        });
    });
    // 重新检查
    $container.on('recheck', (_, data) => {
        //获取表格
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要重新检查的检查', 'error');
        } else {
            $.invokeAction('重新检查', `/api/technician/recheck`, { examId: oids[0] }, { actionUrl: '/api/workflow/invoke' }).then(result => {
                DevExpress.ui.notify('重新检查', 'success');
                refreshDataGrid(data);
            });
        }
    });
    // 取消检查
    $container.on('cancel', (_, data) => {
        //获取表格
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要取消的检查', 'error');
        } else {
            //调用取消接口
            //调用invokeAction
            $.invokeAction('取消检查', `/api/technician/cancel-exam`, { examId: oids[0] }, { actionUrl: '/api/workflow/invoke' }).then(result => {
                if (result.success) {
                    DevExpress.ui.notify('取消成功', 'success');
                    refreshDataGrid(data);
                }
            });
        }
    });
    // 刷新
    $container.on('refresh', (_, data) => {
        //获取表格
        refreshDataGrid(data);
    });
    // 自动刷新
    $container.on('autoRefresh', (_, data) => {
        const { component, key, intervalKey } = data.data;
        component.itemData.text = autoRefresh(key, intervalKey, () => {
            //获取表格
            refreshDataGrid(data);
        });
        component.component.repaint();
    });
    // 刷新间隔时间
    $container.on('refreshInterval', (_, data) => {
        const { key, intervalKey } = data.data;
        refreshInterval(key, intervalKey, () => {
            //获取表格
            refreshDataGrid(data);
        });
    });
    // 检查匹配（检查和未匹配的Study进行匹配）
    $container.on('matchStudy', (_, data) => {
        // 独立的按钮，打开一个页面，进行匹配
        window.open('/technician/match', '检查匹配');
    });
    //匹配选择
    $container.on('matchSelect', (_, data) => {
        debugger;
        //获取表格
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要匹配的检查', 'error');
        } else {
            const _data = data.data;
            let isReport = _data && _data.type === 'report';
            //打开弹窗
            openMatchPopup(isReport).then(examOids => {
                
                if (isReport) {
                    //匹配接口
                    ris.ajax(`/api/match/report/${examOids[0]}`, { type: 'POST', data: { studyIds: oids } }).then(result => {
                        refreshDataGrid(data);
                    });
                } else {
                    //匹配接口
                    ris.ajax(`/api/match/${examOids[0]}`, { type: 'POST', data: { studyIds: oids } }).then(result => {
                        refreshDataGrid(data);
                    });
                }
            });
        }
    });
    //查看报告
    $container.on('viewReport', (_, data) => {
        const { examGrid } = data;
        let result = false;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let reportUrls = rowsData.filter(e => e.isArchive).map(e => e.reportUrl);
        if (reportUrls && reportUrls.length === 0) result= true;
        if (reportUrls && reportUrls.length >= 0) {
            reportUrls.forEach(e => {
                ris.viewReport(e);
            })
        }
        if (rowsData.filter(e => !e.isArchive).length > 0) {
            result= true;
        }
        if (!result) return false;
        let oids = rowsData ? rowsData.filter(e => !e.isArchive).map(e => e.oid) : [];
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要查看报告的检查', 'error');
        } else {
            ris.ajax(`/api/report/get-report-pdf-files`, { type: 'POST', data: { examIds: oids }, errorMessage: '打印服务启动失败' }).then(result => {
                if (result.success) {
                    if (result.error) {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                    result.data.forEach(e => {
                        ris.viewReport(e);
                    })
                } else {
                    DevExpress.ui.notify(result.error, 'error');
                }
            })
        }
    });
    //查看图像
    $container.on('viewImage', (_, data) => {
        const { examGrid } = data;
        let result = false;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let reportImagesPaths = rowsData.filter(e => e.isArchive).map(e => e.reportImagesPath);
        if (reportImagesPaths && reportImagesPaths.length === 0) result = true;
        if (reportImagesPaths && reportImagesPaths.length >= 0) {
            reportImagesPaths.forEach(e => {
                ris.viewReport(e);
            })
        }
        if (rowsData.filter(e => !e.isArchive).length > 0) {
            result = true;
        }
        if (!result) return false;
        let oids = rowsData ? rowsData.filter(e => !e.isArchive).map(e => e.oid) : [];
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要查看图像的检查', 'error');
        } else {
            ris.ajax('/api/exam/get-dicom-client-url').then(result => {
                if (result.success && result.data) {
                    let url = result.data;
                    if (result.data.includes('?')) {
                        url += `&examIds=${oids.join(',')}`;
                    } else {
                        url += `?examIds=${oids.join(',')}`;
                    }
                    ris.viewImage(url);
                } else {
                    DevExpress.ui.notify(result.error, 'error');
                }
            });
        }
    });
    // 挂起
    $container.on('suspend', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要挂起的检查', 'error');
        } else {
            //调用取消接口
            //调用invokeAction
            $.invokeAction(
                '挂起',
                `/api/register/pending`,
                { examIds: oids },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    DevExpress.ui.notify('挂起成功', 'success');
                    refreshDataGrid(data);
                }
            });
        }
    });
    //过号
    $container.on('pass', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要过号的检查', 'error');
        } else {
            $.invokeAction(
                '过号',
                `/api/technician/pass`,
                { examId: oids[0] },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    refreshDataGrid(data);
                }
            });
        }
    });
    $container.on('applyConsultation', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要申请会诊的检查', 'error');
        } else {
            //调用删除接口
            $.invokeAction(
                '申请会诊',
                `/api/study/apply-consultation`,
                { examIds: oids },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    DevExpress.ui.notify('申请成功', 'success');
                    refreshDataGrid(data);
                }
            });
        }
    });
    $container.on('examEvent', (_, data) => {
        const { examGrid } = data;
        let rowsData = (examGrid && examGrid.getSelectedRowsData());
        let oids = rowsData.filter(e => !e.isArchive).map(e => e.oid);
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要查看检查事件的检查', 'error');
        } else if (oids.length !== 1) {
            DevExpress.ui.notify('请选择一个需要查看检查事件的检查', 'error');
        } else {
            openExamEventPopup(oids[0])
        }
    });
    $container.on('export', (_, data) => {
        const { params } = data;
        if (params) {
            const { exportData } = params;
            if (exportData instanceof Function) {
                exportData((loadOptions) => {
                    const exportList = () => {
                        ris.ajax('/api/technician/export', { data: loadOptions, type: 'POST', contentType: 'application/json;charset=UTF-8', dataType: 'json' }).then(result => {
                            if (result.data) {
                                window.open(`/api/export-list/${result.data}?fileName=检查表`, '_blank');
                            }
                        });
                    };
                    if (data.examGrid.totalCount() > 1000) {
                        DevExpress.ui.dialog.confirm("导出数据过多，是否继续导出？", "导出列表").done(result => {
                            if (result) {
                                exportList();
                            }
                        })
                    } else {
                        exportList();
                    }
                })
            }
        }
    });
    const verifyArchive = (data) => {
        return new Promise((resolve, reject) => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            if (rowsData && rowsData.length > 0) {
                var isArchive = rowsData.filter(e => e.isArchive);
                if (isArchive.length > 0) {
                    DevExpress.ui.notify('存在已归档的数据', 'error');
                    reject();
                }
            }
            resolve();
        })
    }
    //打开设备更换弹窗
    const openDevicePopup = (oid) => {
        return new Promise((resolve, reject) => {
            let dataGrid;
            const popup = $('<div>').appendTo('body')
                .dxPopup({
                    width: '50%',
                    height: '60%',
                    container: 'body',
                    showTitle: true,
                    title: `设备列表`,
                    visible: true,
                    dragEnabled: false,
                    toolbarItems: [
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '确定',
                                onClick: () => {
                                    if (dataGrid) {
                                        const deviceOids = dataGrid.getSelectedRowKeys();
                                        if (deviceOids.length === 0) {
                                            DevExpress.ui.notify('请选择需要更换的设备', 'error');
                                        } else if (deviceOids.length > 1) {
                                            DevExpress.ui.notify('只能选择一个设备', 'error');
                                        } else {
                                            //确定匹配
                                            resolve(deviceOids);
                                            popup.hide();
                                        }
                                    }
                                },
                            },
                        },
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '取消',
                                onClick: () => {
                                    popup.hide();
                                },
                            },
                        },
                    ],
                    position: {
                        at: 'center',
                        my: 'center',
                        collision: 'fit',
                    },
                    contentTemplate: container => {
                        const $contentDiv = $('<div class="p-c"><div />').appendTo(container);
                        //表格
                        dataGrid = $('<div class="p-datagrid"><div />').appendTo($contentDiv).dataGrid({
                            key: 'id',
                            selection: { mode: 'single' },
                            columnAutoWidth: true,
                            // key:'',
                            onLoad(e) {
                                //根据data返回的数据查询检查列表
                                let sort = null;
                                if (e.sort instanceof Array && e.sort.length > 0) {
                                    sort = `?sortProperty=${e.sort[0].selector}&sortMode=${e.sort[0].desc}`;
                                }
                                return $.get(`/api/devices/get-by-exam/${oid}${sort ?? ''}`);
                            }
                        })
                    },
                    onHidden(e) {
                        //关闭时销毁
                        e.component.dispose();
                        $(e.element).remove();
                    },
                }).dxPopup('instance');
        })
    };
    //打开匹配弹窗
    const openMatchPopup = (isReport) => {
        return new Promise((resolve, reject) => {
            let dataGrid;
            const popup = $('<div>').appendTo('body')
                .dxPopup({
                    width: '85%',
                    height: '90%',
                    container: 'body',
                    showTitle: true,
                    title: `检查列表`,
                    visible: true,
                    dragEnabled: false,
                    toolbarItems: [
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '确定',
                                onClick: () => {
                                    if (dataGrid) {
                                        const examOids = dataGrid.getSelectedRowKeys();
                                        if (examOids.length === 0) {
                                            DevExpress.ui.notify('请选择需要匹配的检查', 'error');
                                        } else if (examOids.length > 1) {
                                            DevExpress.ui.notify('只能选择一个检查数据', 'error');
                                        } else {
                                            //确定匹配
                                            resolve(examOids);
                                            popup.hide();
                                        }
                                    }
                                },
                            },
                        },
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '取消',
                                onClick: () => {
                                    popup.hide();
                                },
                            },
                        },
                    ],
                    position: {
                        at: 'center',
                        my: 'center',
                        collision: 'fit',
                    },
                    contentTemplate: container => {
                        const $contentDiv = $('<div class="p-c"><div />').appendTo(container);
                        //高级搜索
                        const advancedSearch = $('<div />').appendTo($contentDiv).advancedSearchWithCollapse(null, (e) => {
                            dataGrid.refresh({ userData: e });
                        });
                        $.get('/api/match/get-exam-advanced-search-view').then(result => {
                            if (result.success) {
                                if (result.view) {
                                    advancedSearch.updateView(result.view);
                                }
                            }
                        });
                        //表格
                        dataGrid = $('<div class="p-datagrid"><div />').appendTo($contentDiv).examGrid({
                            selection: { mode: 'single' },
                            onLoad(loadOptions) {
                                if (isReport) {
                                    return $.post({
                                        dataType: 'json',
                                        contentType: 'application/json;charset=UTF-8',
                                        url: `/api/match/get-report-exams`,
                                        data: JSON.stringify(loadOptions)
                                    });
                                } else {
                                    return $.post({
                                        dataType: 'json',
                                        contentType: 'application/json;charset=UTF-8',
                                        url: `/api/match/get-exams`,
                                        data: JSON.stringify(loadOptions)
                                    });
                                }
                            }
                        })
                    },
                    onHidden(e) {
                        //关闭时销毁
                        e.component.dispose();
                        $(e.element).remove();
                    },
                }).dxPopup('instance');
        })
    };
    const refreshDataGrid = (data) => {
        //获取表格
        const { params } = data;
        if (params) {
            const { reloadGrid } = params;
            if (reloadGrid instanceof Function) {
                reloadGrid();
            }
        } else {
            const { examGrid } = data;
            examGrid.refresh();
        }
    }
    const openExamEventPopup = (examId) => {
        const popup = $('<div>')
            .appendTo('body')
            .dxPopup({
                width: '40%',
                height: '40%',
                minWidth: '700px',
                minHeight: '500px',
                container: 'body',
                showTitle: true,
                title: `检查事件`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                toolbarItems: [{
                    location: 'after',
                    toolbar: 'bottom',
                    widget: 'dxButton',
                    options: {
                        text: '关闭',
                        onClick: () => {
                            popup.hide();
                        },
                    },
                }],
                contentTemplate: container => {
                    const $contentDiv = $('<div class="p-c"></div>').appendTo(container);
                    //表格
                    $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            paging: { enabled: false },
                            pager: { visible: false },
                            remoteOperations: false,
                            onLoad(loadOptions) {
                                return new Promise((resolve, reject) => {
                                    $.get({
                                        url: `/api/exam-event/get-exam-events?examId=${examId}`,
                                        success: result => {
                                            if (result.success) {
                                                resolve(result)
                                            } else {
                                                reject(result.error);
                                            }
                                        }
                                    });
                                })
                            }
                        });
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    }
});
